package com.sunway.logger.service;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class IndexServiceImpl implements IndexService {

	@Autowired
	private TransportClient client;

	@Override
	public <T> IndexResponse save(T pojo) throws JsonProcessingException {
		// instance a json mapper
		ObjectMapper mapper = new ObjectMapper(); // create once, reuse

		IndexResponse ir = null;

		// generate a json content
		String jsonString = mapper.writeValueAsString(pojo);
		
		// indexing document
		//@formatter:off
		ir = client
				.prepareIndex("estandard", pojo.getClass().getSimpleName())
				.setSource(jsonString, XContentType.JSON ).get();

		//@formatter:on
		return ir;
	}
	
	

}
